﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace CustomVirtualizingPanel
{
    /// <summary>
    /// 简单的自定义容器
    /// 子元素在垂直方向布满容器，水平方向平局分配容器宽度
    /// </summary>
    public class SplitPanel : Panel
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (UIElement child in InternalChildren)
            {
                child.Measure(availableSize);   // 测量子元素期望布局尺寸(child.DesiredSize)
            }

            return base.MeasureOverride(availableSize);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            if (double.IsInfinity(finalSize.Height) || double.IsInfinity(finalSize.Width))
            {
                throw new InvalidOperationException("容器的宽和高必须是确定值");
            }

            if (Children.Count > 0)
            {
                double childAverageWidth = finalSize.Width / Children.Count;
                for (int childIndex = 0; childIndex < InternalChildren.Count; childIndex++)
                {
                    // 计算子元素将被安排的布局区域
                    var rect = new Rect(childIndex * childAverageWidth, 0, childAverageWidth, finalSize.Height);
                    InternalChildren[childIndex].Arrange(rect);
                }
            }

            return base.ArrangeOverride(finalSize);
        }
    }
}
